package org.ushio.speech_module.speech.sentence;

import org.ushio.speech_module.notification.NotificationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

/**
 * @author 陈红
 */
@Service
@Slf4j
public class SentenceService {

    @Autowired
    private SentenceMapper sentenceMapper;

    @Autowired
    private NotificationService notificationService;

    @Transactional(readOnly = true)
    public Sentence findById(Long id) {
        return sentenceMapper.findById(id);
    }

    @Transactional(readOnly = true)
    public List<Sentence> findAll() {
        return sentenceMapper.findAll();
    }

    @Transactional(rollbackFor = {IOException.class})
    public int insertSentence(Sentence sentence, MultipartFile audioFile) throws IOException {
        try {
            if (!audioFile.isEmpty()) {
                byte[] audioBytes = audioFile.getBytes();
                sentence.setAudio(audioBytes);
            }
            String message = sentence.getChapterId() + "章节内容有增加噢!";
            notificationService.createNotification(message);
            return sentenceMapper.insert(sentence);
        } catch (IOException e) {
            log.error("Error processing audio file for sentence insertion: {}", e.getMessage(), e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw e;
        }
    }

    @Transactional(rollbackFor = {IOException.class})
    public int updateSentence(Sentence sentence, MultipartFile audioFile) throws IOException {
        try {
            // 如果传入了音频文件且文件不为空，则更新音频内容
            if (audioFile != null && !audioFile.isEmpty()) {
                byte[] audioBytes = audioFile.getBytes();
                sentence.setAudio(audioBytes);
            }
            // 更新句子
            String message = sentence.getChapterId() + "章节内容有更改噢!";
            notificationService.createNotification(message);
            return sentenceMapper.update(sentence);
        } catch (IOException e) {
            log.error("Error processing audio file for sentence update: {}", e.getMessage(), e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw e;
        }
    }


    @Transactional
    public int deleteById(Long id) {
        return sentenceMapper.deleteById(id);
    }

    @Transactional(readOnly = true)
    public List<Sentence> findByChapterId(Long chapterId) {
        return sentenceMapper.findByChapterId(chapterId);
    }
}

